// import { importFile } from '@/api/upload'
import { getOssData, sendOssData } from '@/api/common'
class myUploadAdapter {
  loader
  constructor(loader) {
    // The file loader instance to use during the upload.
    this.loader = loader
  }

  // Starts the upload process.
  upload() {
    return this.loader.file.then(
      (file) =>
        new Promise((resolve) => {
          this.uploadFile(file, resolve)
        })
    )
  }

  // async uploadFile(file, resolve) {
  //   // 上传文件
  //   // this.handleUpload(file, resolve)
  //   // const formData = new FormData()
  //   // formData.append('files', file)
  //   // try {
  //   //   const res = await importFile(formData)
  //   //   const obj = {
  //   //     default: res[0],
  //   //   }
  //   //   resolve(obj)
  //   // } finally {
  //   // }
  // }

  // Aborts the upload process.
  abort() {
    // Reject the promise returned from the upload() method.
    // server.abortUpload();
  }
  async uploadFile(file, cb) {
    // 生成文件名，作为 key 使用
    const generateFileName = (ossData, file) => {
      const suffix = file.name.slice(file.name.lastIndexOf('.'))
      const filename = Date.now() + suffix
      return ossData.dir + filename
    }
    const ossData = await getOssData()
    const key = generateFileName(ossData, file)
    const formdata = new FormData()
    // 注意参数的顺序，key 必须是第一位，表示OSS存储文件的路径
    formdata.append('key', key)
    formdata.append('OSSAccessKeyId', ossData.accessId)
    formdata.append('policy', ossData.policy)
    formdata.append('signature', ossData.signature)
    // 文件上传成功默认返回 204 状态码，可根据需要修改为 200
    formdata.append('success_action_status', '200')
    // file 必须放在最后一位
    formdata.append('file', file)
    const res = await sendOssData(ossData.host, formdata)
    if (res.status === 200) {
      cb({ default: ossData.host + '/' + key })
    }
  }
}
export default myUploadAdapter
